#coding:utf8
#
# Author: CMGS
# Created on 2010-12-3
#

import json
import threading

from common import config as _config
from libs import memory as _memory
from libs.debugger import Debugger

class Spy(object):
    
    def __init__(self):
        self._pools = {}
        self._lock = threading.RLock()
        size = _config.SPY_POOL_DEFAULT_SIZE
        for pool in _config.SPY_POOLS:
            if len(pool) == 1:
                # 默认情况
                self._pools[pool[0]] = _memory.MemoryPool(size)
            elif len(pool) == 2 and isinstance(pool[1], int):
                # 定义了pool size
                self._pools[pool[0]] = _memory.MemoryPool(pool(1))
            else:
                Debugger.out(pool)
    
    def record(self, pool, k, v):
        Debugger.out(pool, k, v)
        self._lock.acquire()
        try:
            value = json.loads(v)
            if not self._pools[pool].add(k, [value]):
                self._pools[pool].get(k).append(value)
        except Exception, e:
            Debugger.exc(e)
        self._lock.release()

    def getRecord(self, pool, b = 0, e = 12345678910):
        indexList = self._pools[pool].getIndex()
        ret = {}
        for t in indexList:
            if int(t) > int(b) and int(t) < int(e):
                ret[t] = self._pools[pool].get(t)
        return ret

if __name__ == '__main__':
    import time
    spy = Spy()
    print spy._pools
    for i in range(1, 20):
        spy.record('requestDownload', time.time(), json.dumps({'i': i}))
    print spy._pools['requestDownload'].getMany()
